package cn.matezk.lianlian.framework;

import cn.hutool.core.util.ObjectUtil;
import cn.matezk.lianlian.beans.ForbiddenException;
import cn.matezk.lianlian.beans.NoauthException;
import cn.matezk.lianlian.beans.Result;
import cn.matezk.lianlian.beans.TerminalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.util.NestedServletException;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public ResponseEntity<Result> handlerException(Exception e) {
        log.error("全局异常捕获", e);
        if (e instanceof HttpRequestMethodNotSupportedException) {
            return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body(new Result(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), e.getMessage(), null));
        } else if (e instanceof NestedServletException) {
            String msg = e.getMessage();
            if (ObjectUtil.isNotEmpty(msg) && msg.indexOf("java.lang.InternalError: ") >= 0)
                msg = msg.substring(msg.indexOf("java.lang.InternalError: ") + "java.lang.InternalError: ".length());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(msg));
        } else if (e instanceof TerminalException) {
            TerminalException ex = (TerminalException)e;
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(ex.getMsg()));
        } else if (e instanceof ForbiddenException) {
            ForbiddenException ex = (ForbiddenException)e;
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new Result(HttpStatus.FORBIDDEN.value(), ex.getMsg(), null));
        } else if (e instanceof NoauthException) {
            NoauthException ex = (NoauthException)e;
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new Result(HttpStatus.UNAUTHORIZED.value(), ex.getMsg(), null));
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(e.getMessage()));
    }
}
